import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:dart_mock/dart_mock.dart' as mock;
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:provider/provider.dart';
import 'package:qianyi/controller/homeTabController.dart';
import 'package:qianyi/controller/imageController.dart';
import 'package:qianyi/network/http_manager.dart';
import 'package:qianyi/state/token.dart';
import 'package:qianyi/utils/throttle.dart';
import 'package:qianyi/view_model/home/recommend/recommend_tag_view_model.dart';
import 'package:qianyi/wcao/kit/index.dart';
import 'package:qianyi/wcao/ui/theme.dart';
import 'package:shimmer_animation/shimmer_animation.dart';

import '../../../../controller/webSockerController.dart';
import '../../../../entity/message/MessageChat.dart';
import '../../../../network/http_config.dart';
import '../../../../ui/widget/custom_refresh.dart';
import '../../../../view_model/message/message_chat_view_model.dart';

/// HACK: 消息-聊天

class MessageChat extends StatefulWidget {
  const MessageChat({Key? key}) : super(key: key);

  @override
  State<MessageChat> createState() => _MessageChatState();
}

class _MessageChatState extends State<MessageChat> with TickerProviderStateMixin{
  HomeTabController homeTabController = Get.find();
  TokenController tokenController = Get.find();
  MessageChatViewModel? messageChatViewModel;
  WebSocketController webSocketController = Get.find();

  final FocusScopeNode _focusScopeNode = FocusScopeNode();
  bool isLoad = true;
  TextEditingController textEditingController = TextEditingController();
  ImageAvatarController imageAvatarController = Get.find();
  @override
  void initState() {
    super.initState();

    getImageAvatar();
  }
  getImageAvatar() {

  }
  requestModel() {
    textEditingController.clear();
    _focusScopeNode.unfocus();

    this.messageChatViewModel!.onRefresh();

    setState(() {
      
    });
  }

  @override
  void dispose() {
    textEditingController.dispose();
    _focusScopeNode.dispose();

    // TODO: implement dispose
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {

    // imageAvatarController.isLoad.value? Shimmer(
    //   duration: Duration(seconds: 1), //Default value
    //   interval: Duration(seconds: 1), //Default value: Duration(seconds: 0)
    //   color: Colors.grey, //Default value
    //   colorOpacity: 0.3, //Default value
    //   enabled: true, //Default value
    //   direction: ShimmerDirection.fromLTRB(),  //Default Value
    //   child: Container(
    //     color: Colors.white,
    //   ),
    // ):

    // Scaffold(
    //
    //   appBar: AppBar(
    //     title: const Text('好友名称'),
    //     actions: [
    //       IconButton(
    //         onPressed: () {
    //           showCupertinoModalPopup(
    //             context: context,
    //             builder: (context) => SafeArea(
    //               child: Column(
    //                 mainAxisAlignment: MainAxisAlignment.end,
    //                 children: [
    //                   CupertinoActionSheet(
    //                     actions: [
    //                       CupertinoActionSheetAction(
    //                         onPressed: () {
    //                           Navigator.pop(context);
    //                         },
    //                         child: const Text("拉黑"),
    //                       ),
    //                       CupertinoActionSheetAction(
    //                         onPressed: () {
    //                           Navigator.pop(context);
    //                         },
    //                         child: const Text(
    //                           "举报",
    //                           style: TextStyle(color: Colors.redAccent),
    //                         ),
    //                       ),
    //                     ],
    //                   ),
    //                   CupertinoActionSheet(
    //                     actions: [
    //                       CupertinoActionSheetAction(
    //                         onPressed: () {
    //                           Navigator.pop(context);
    //                         },
    //                         child: Text(
    //                           "取消",
    //                           style: TextStyle(color: WcaoTheme.placeholder),
    //                         ),
    //                       )
    //                     ],
    //                   ),
    //                 ],
    //               ),
    //             ),
    //           );
    //         },
    //         icon: const Icon(Icons.more_horiz),
    //       )
    //     ],
    //   ),
    //   body: Column(
    //     children: [
    //       Expanded(child:
    //       ChangeNotifierProvider(
    //           create: (BuildContext context) => MessageChatViewModel(),
    //           child: Consumer<MessageChatViewModel>(
    //             builder: (context, viewModel, child) {
    //               webSocketController.messageChatViewModel = viewModel;
    //               messageChatViewModel = viewModel;
    //               return CustomRefresh(
    //                   isMaterialHeader:true,
    //                   controller: viewModel.refreshController,
    //
    //                   enablePullUp: true
    //                   ,
    //                   enablePullDown: true,
    //                   onRefresh: () async {
    //                     viewModel.onRefresh();
    //                   },
    //                   onLoading: () async {
    //
    //                     viewModel.onLoading();
    //                   },
    //                   child:
    //                   // SingleChildScrollView(
    //                   //     child:
    //                   ListView.builder(
    //                     reverse: true,
    //                     // , // 设置为true，使ListView滑动方向相反
    //
    //                     itemCount: viewModel.datas.length,
    //                     padding: const EdgeInsets.symmetric(horizontal: 24),
    //                     itemBuilder: (context, index) {
    //                       MessageChatRecord messageChat = viewModel.datas[index];
    //
    //                       return msgItem(messageChat);
    //                     },
    //                   )
    //                 // ),
    //
    //               )
    //
    //               ;
    //             },
    //           )
    //
    //       )
    //       ),
    //       Row(
    //         mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    //         children: <Widget>[
    //           IconButton(
    //             icon: Icon(Icons.menu),
    //             onPressed: () {
    //               // Handle menu press
    //             },
    //           ),
    //           Expanded(
    //             child: TextField(
    //               focusNode: _focusScopeNode,
    //
    //               controller: textEditingController,
    //               keyboardType: TextInputType.text,
    //               obscureText: false,
    //               enableSuggestions: false,
    //               autocorrect: false,
    //               decoration: InputDecoration(
    //                 hintText: "发送消息...",
    //                 contentPadding: EdgeInsets.symmetric(
    //                   vertical: 0,
    //                   horizontal: 16,
    //                 ),
    //                 enabledBorder: OutlineInputBorder(
    //                   borderSide: BorderSide.none,
    //                 ),
    //                 focusedBorder: OutlineInputBorder(
    //                   borderSide: BorderSide.none,
    //                 ),
    //               ),
    //             ),
    //           ),
    //           IconButton(
    //             icon: Icon(Icons.send),
    //             onPressed: () {
    //               HudUtil.showSend();
    //               String acceptId = homeTabController.messageItem!.sendId!;
    //               String sendId = tokenController.uid;
    //               if(textEditingController.text.length < 0) return;
    //               String content = textEditingController.text;
    //               Map<String,dynamic> parms = {
    //                 "acceptId":acceptId,
    //                 "sendId":sendId,
    //                 "content": textEditingController.text
    //               };
    //               HttpManager.getInstance().request(url: '/platform/chat/addChatRecord',method: Method.post,params: parms).then((res) => {
    //
    //                 HudUtil.dismiss(),
    //                 requestModel()
    //               }).catchError((onError)=>{
    //                 print(onError)
    //               });
    //               // Handle send press
    //             },
    //           ),
    //         ],
    //       )
    //     ],
    //   )
    //
    //
    //   ,
    // )
    return Scaffold(

      appBar: AppBar(
        title: const Text('好友名称'),
        actions: [
          IconButton(
            onPressed: () {
              showCupertinoModalPopup(
                context: context,
                builder: (context) => SafeArea(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      CupertinoActionSheet(
                        actions: [
                          CupertinoActionSheetAction(
                            onPressed: () {
                              Navigator.pop(context);
                            },
                            child: const Text("拉黑"),
                          ),
                          CupertinoActionSheetAction(
                            onPressed: () {
                              Navigator.pop(context);
                            },
                            child: const Text(
                              "举报",
                              style: TextStyle(color: Colors.redAccent),
                            ),
                          ),
                        ],
                      ),
                      CupertinoActionSheet(
                        actions: [
                          CupertinoActionSheetAction(
                            onPressed: () {
                              Navigator.pop(context);
                            },
                            child: Text(
                              "取消",
                              style: TextStyle(color: WcaoTheme.placeholder),
                            ),
                          )
                        ],
                      ),
                    ],
                  ),
                ),
              );
            },
            icon: const Icon(Icons.more_horiz),
          )
        ],
      ),
      body: Column(
        children: [
          Expanded(child:
          ChangeNotifierProvider(
              create: (BuildContext context) => MessageChatViewModel(),
              child: Consumer<MessageChatViewModel>(
                builder: (context, viewModel, child) {
                  webSocketController.messageChatViewModel = viewModel;
                  messageChatViewModel = viewModel;
                  return CustomRefresh(
                      isMaterialHeader:true,
                      controller: viewModel.refreshController,

                      enablePullUp: true
                      ,
                      enablePullDown: true,
                      onRefresh: () async {
                        viewModel.onRefresh();
                      },
                      onLoading: () async {

                        viewModel.onLoading();
                      },
                      child:
                      // SingleChildScrollView(
                      //     child:
                      ListView.builder(
                        reverse: true,
                        // , // 设置为true，使ListView滑动方向相反

                        itemCount: viewModel.datas.length,
                        padding: const EdgeInsets.symmetric(horizontal: 24),
                        itemBuilder: (context, index) {
                          MessageChatRecord messageChat = viewModel.datas[index];

                          return msgItem(messageChat);
                        },
                      )
                    // ),

                  )

                  ;
                },
              )

          )
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              IconButton(
                icon: Icon(Icons.menu),
                onPressed: () {
                  // Handle menu press
                },
              ),
              Expanded(
                child: TextField(
                  focusNode: _focusScopeNode,

                  controller: textEditingController,
                  keyboardType: TextInputType.text,
                  obscureText: false,
                  enableSuggestions: false,
                  autocorrect: false,
                  decoration: InputDecoration(
                    hintText: "发送消息...",
                    contentPadding: EdgeInsets.symmetric(
                      vertical: 0,
                      horizontal: 16,
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderSide: BorderSide.none,
                    ),
                    focusedBorder: OutlineInputBorder(
                      borderSide: BorderSide.none,
                    ),
                  ),
                ),
              ),
              IconButton(
                icon: Icon(Icons.send),
                onPressed: () {
                  HudUtil.showSend();
                  String acceptId = homeTabController.messageItem!.sendId!;
                  String sendId = tokenController.uid;
                  if(textEditingController.text.length <= 0) return;
                  String content = textEditingController.text;
                  Map<String,dynamic> parms = {
                    "acceptId":acceptId,
                    "sendId":sendId,
                    "content": textEditingController.text
                  };
                  HttpManager.getInstance().request(url: '/platform/chat/addChatRecord',method: Method.post,params: parms).then((res) => {

                    HudUtil.dismiss(),
                    requestModel()
                  }).catchError((onError)=>{
                    print(onError)
                  });
                  // Handle send press
                },
              ),
            ],
          )
        ],
      )


      ,
    )
      ;
  }

  Container msgItem(MessageChatRecord messageChat) {
    ImageAvatarController imageAvatarController = Get.find();
    // 根据消息发送者调整布局
    EdgeInsets margin;
    Widget messageWidget;

    if (tokenController.uid == messageChat.sendId) {
      // 如果是本人发送的消息，显示在右边
      margin = const EdgeInsets.only(right: 12);
      messageWidget = Flexible(child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: Colors.orange,
          borderRadius: BorderRadius.circular(12),
        ),
        margin: margin,
        child: Text(
          softWrap: true, // 默认就是true，支持自动换行
          '${messageChat.content}',
          style: const TextStyle(color: Colors.white),
          textAlign: TextAlign.right, // 文字右对齐
        ),
      ));
    } else {
      // 如果是其他人发送的消息，显示在左边
      margin = const EdgeInsets.only(left: 12);
      messageWidget = Flexible(child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
        decoration: BoxDecoration(
          color: Colors.grey, // 假设这是接收到的消息颜色
          borderRadius: BorderRadius.circular(12),
        ),
        margin: margin,
        child: Text(
          '${messageChat.content}',
          style: const TextStyle(color: Colors.black), // 假设这是接收到的消息文字颜色
        ),
      ))
          ;
    }
    Widget avatarWidget = Obx(() => CircleAvatar(
      backgroundImage: imageAvatarController.avatarImages.length==0
          ? NetworkImage(messageChat.avatar!) as ImageProvider<Object>?
          : MemoryImage(imageAvatarController.avatarImages[0].bytes ),
    ))
    ;

    Widget avatarWidgetright = Obx(() => CircleAvatar(
      backgroundImage: imageAvatarController.avatarImages.length<=1
          ?
      NetworkImage(messageChat.avatar!) as ImageProvider<Object>?
          : MemoryImage(imageAvatarController.avatarImages[1].bytes ),
    ),

    );
    // 头像组件

    return Container(
      padding: const EdgeInsets.symmetric(vertical: 12),
      child: Row(
        mainAxisAlignment: tokenController.uid == messageChat.sendId ? MainAxisAlignment.end : MainAxisAlignment.start,
        children: tokenController.uid == messageChat.sendId ? [messageWidget, avatarWidget] : [avatarWidgetright, messageWidget],
      ),
    );
  }


}
